<!--
+----------------------------------------------------------------------
| 友得云客  - 开启房产营销新纪元
+----------------------------------------------------------------------
| Copyright (c) 2019~2023 优得（西安）信息科技有限公司版权所有
+----------------------------------------------------------------------
| Licensed 友得云客不是自由软件 未经允许不可移除相关版权
+----------------------------------------------------------------------
| Author: www.youdeyunke.com
+----------------------------------------------------------------------
-->
<template>
    <div class="app-container">
        <actions ref="actions"></actions>
        <ud-card>
            <div class="myheader">
                <div class="part-left">
                    <div class="block">
                        <el-radio-group v-model="scopeValue" :disabled="listLoading" size="small" placeholder="请选择">
                            <el-radio-button v-for="(item, index) in scopeItems" :key="index" :label="item.value">{{
                                item.name }}</el-radio-button>
                        </el-radio-group>
                    </div>

                    <div class="block">
                        <el-date-picker v-model="dateRange" size="small" type="daterange" range-separator="至"
                            start-placeholder="选择开始日期" end-placeholder="选择结束日期" />
                    </div>

                    <div class="block">
                        <!-- <user-selector size="small" @change="loadData" v-model="userId"></user-selector> -->
                        <el-input v-model="kw" style="border-radius: 100%; width: 250px" size="small"
                            placeholder="输入uid、手机号搜索">
                            <el-button slot="append" icon="el-icon-search" @click="doSearch" />
                        </el-input>
                        <!-- <el-button v-if="kw" type="text" size="small" @click="clearKw">清空</el-button> -->
                    </div>

                    <div class="block">
                        <el-button v-if="dateRange || searchKw" type="text" size="small"
                            @click="clearFilter">清空过滤条件</el-button>
                    </div>
                </div>

                <div class="part-right">
                    <div class="block">
                        <el-button size="small" @click="loadData" icon="el-icon-refresh">刷新</el-button>
                        <el-button size="small" type="primary"  @click="downloadCsv" icon="el-icon-download" :loading="exportLoading" :disabled="exportLoading">导出数据</el-button>
                    </div>
                </div>
            </div>
            <el-divider></el-divider>
            <el-table v-loading="listLoading" style="width: 100%" :data="visitors" size="small"
                element-loading-text="正在加载访客数据" fit highlight-current-row>
                <el-table-column label="#" prop="id" width="80"> </el-table-column>
                <el-table-column label="IP" prop="ip" width="160"> </el-table-column>
                <el-table-column label="IP归属地" prop="ip_region" width="200"> </el-table-column>
                <el-table-column label="uid" prop="uid"> </el-table-column>
                <el-table-column label="用户" prop="username" :width="180">
   
                </el-table-column>
                <el-table-column prop="seconds" label="停留时长" width="120">
                    <template slot-scope="{ row }">
                        {{ formatDuration(row.seconds) }}
                    </template>
                </el-table-column>
                <el-table-column prop="updated_at" label="最新活动时间" width="150" />
                <el-table-column width="100">
                    <template slot-scope="scope">
                        <el-link :disabled="scope.row.actions_count.length == 0" type="primary" size="small"
                            @click="actionsHandle(scope.row)">明细({{ scope.row.actions_count }})</el-link>
                    </template>
                </el-table-column>
            </el-table>

            <div class="pager">
                <el-pagination hide-on-single-page background layout="total, sizes, prev, pager, next, jumper" :total="total"
                    :page-sizes="[10, 20, 50, 100]" :page-size="per_page" @current-change="updateCurrentPage"
                    @size-change="updatePageSize" />
            </div>
        </ud-card>
    </div>
</template>

<style lang="scss" scoped>
.app-container {
    .user-block {
        display: flex;
        align-items: center;

        .name {
            margin-left: 10px;
        }
    }

    .myheader {
        display: flex;
        justify-content: space-between;
        align-items: center;
        // padding: 20px 0px;

        .part-left {
            display: flex;
            justify-content: flex-start;
            align-items: center;

            .block {
                margin-right: 10px;
            }
        }

        .el-input {
            width: 250px;
            border-radius: 100%;
        }
    }
}
</style>

<script>
import { getVisitorList, exportData, } from "@/api/visitor";
import { getToken } from "@/utils/auth";
import UserSelector from "@/components/UserSelector";
import UdCard from "@/components/UdCard";
import Actions from "./Actions";
export default {
    name: "visitors",
    components: { UserSelector, UdCard, Actions },

    data: function () {
        return {
            dateRange: null,
            searchKw: "",
            scopeItems: [
                { name: "今天", value: "today_items" },
                { name: "昨天", value: "yesterday_items" },
                { name: "7天内", value: "week_items" },
                { name: "本月", value: "this_month_items" },
                { name: "上月", value: "last_month_items" },
                { name: "全部", value: "all" },
            ],
            scopeValue: "today_items",
            kw: "",
            // userId: null,
            searchKw: "",
            visitors: [],
            listLoading: true,
            exportLoading: false,
            per_page: 20,
            total: 0,
            current_page: 1,
        };
    },

    computed: {
        date_range_str: function () {
            if (!this.dateRange) {
                return "";
            }
            var d1 = new Date(this.dateRange[0]);
            var d2 = new Date(this.dateRange[1]);
            return d1.toLocaleDateString() + "," + d2.toLocaleDateString();
        },
    },

    watch: {
        dateRange: function (newValue, oldValue) {
            this.scopeValue = "all";
            this.current_page = 1;
            this.loadData();
        },

        scopeValue: function (newValue, oldValue) {
            this.current_page = 1;
            this.loadData();
        },

        current_page: function (newVal, oldVal) {
            this.loadData();
        },
        per_page: function (newVal, oldVal) {
            this.loadData();
        },
    },

    created () {
        this.loadData();
    },

    methods: {
        actionsHandle: function (v) {
            this.$refs.actions.openDialog(v.uid)
        },
        doSearch: function () {
            // 搜索
            this.loading = true;
            this.current_page = 1;
            this.searchKw = this.kw;
            this.loadData();
        },

        formatDuration(seconds) {
            if (seconds < 60) {
                return `${seconds}秒`;
            } else if (seconds < 3600) {
                const minutes = Math.floor(seconds / 60);
                return `${minutes}分钟`;
            } else {
                const hours = Math.floor(seconds / 3600);
                return `${hours}小时`;
            }
        },

        clearFilter: function () {
            this.dateRange = null;
            this.page = 1;
            this.searchKw = "";
            this.kw = "";
            // this.userId = null;
            this.scopeValue = this.scopeItems[0]["value"];
            this.loadData();
        },

        updateCurrentPage: function (page) {
            this.current_page = page;
        },

        updatePageSize: function (size) {
            this.per_page = size || 10;
        },

        loadData: function () {
            this.listLoading = true;
            var _this = this;
            getVisitorList({
                order: "id desc",
                date_range: this.date_range_str,
                scope: _this.scopeValue,
                page: _this.current_page,
                per_page: _this.per_page,
                // user_id: _this.userId,
                kw: _this.searchKw || "",
            }).then((resp) => {
                _this.visitors = resp.data.result;
                _this.total = resp.data.page.total_items;
                _this.listLoading = false;
            });
        },

        downloadCsv: function () {
            var _this = this;
            var tk = getToken();
            var url = "/api/admin/visitors?cmd=download&token=" + tk;
            var query = {
                order: "id desc",
                date_range: this.date_range_str,
                scope: _this.scopeValue,
                // user_id: _this.userId,
                kw: _this.searchKw || "",
            }
            this.exportLoading = true;
            exportData(query).then((res) =>{
                this.exportLoading = false;
                    const blob = new Blob([res], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });

                    // 创建一个a标签
                    const link = document.createElement('a');
                    link.href = URL.createObjectURL(blob); // 设置文件的URL
                    link.download = '访客表.xlsx'; // 设置文件的下载名称

                    // 模拟用户点击链接进行下载
                    link.click();

                    // 释放URL对象
                    URL.revokeObjectURL(link.href);
                })
                .finally(() => {
                    this.exportLoading = false;
                    this.listLoading = false;
                });

        },
    },
};
</script>
